package com.chenxinzhimusic.api

import com.chenxinzhimusic.entity.KuWoResponse
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.engine.android.Android
import io.ktor.client.plugins.HttpTimeout
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.client.plugins.defaultRequest
import io.ktor.client.request.HttpRequestBuilder
import io.ktor.client.request.get
import io.ktor.client.request.header
import io.ktor.client.request.post
import io.ktor.http.ContentType
import io.ktor.serialization.kotlinx.KotlinxSerializationConverter
import io.ktor.serialization.kotlinx.json.json
import kotlinx.serialization.json.Json

/**
 * @description
 * @author chenxinzhi
 * @date 2024/9/18
 */
object KtorHttpClient {
    val CLIENT = HttpClient(Android) {
        defaultRequest {
            header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36")
        }
        install(HttpTimeout) {
            requestTimeoutMillis = 2000
            connectTimeoutMillis = 2000
            socketTimeoutMillis = 2000
        }
        install(ContentNegotiation) {
            json(Json {
                prettyPrint = true
                isLenient = true
                ignoreUnknownKeys = true
            })
            register(
                ContentType.Text.Plain, KotlinxSerializationConverter(
                    Json {
                        prettyPrint = true
                        isLenient = true
                        ignoreUnknownKeys = true
                    }
                )
            )

        }


    }


    suspend inline fun <reified T> getAndFallBack(
        fallbackKuWoResponse: T?,
        builder: HttpRequestBuilder.() -> Unit,
    ): T? {


        return try {
            CLIENT.get(builder)
                .body()
        } catch (e: Exception) {
            fallbackKuWoResponse
        }


    }

    suspend inline fun <reified T> postAndFallBack(
        fallbackKuWoResponse: KuWoResponse<T> = KuWoResponse(),
        builder: HttpRequestBuilder.() -> Unit,
    ): KuWoResponse<T> {
        return try {
            CLIENT.post(builder)
                .body()
        } catch (e: Exception) {
            fallbackKuWoResponse
        }
    }
}